﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XQ.WeChatOfficialAccount.DAL;
using XQ.WeChatOfficialAccount.DAL.DAL;
using XQ.Framework.core;
using XQ.Framework.http;

namespace XQ.WeChatOfficialAccount.WebAPI.Common.WorkContext
{
    /// <summary>
    /// PC前台工作上下文类
    /// </summary>
    public class WebWorkContext : IDisposable
    {
        public const string SESSION_KEY = "LOGIN_USER_SESSION_KEY";
        public const string SESSION_ROLE = "LOGIN_USER_ROLE_KEY";
        public const string COOKIE_KEY = "LOGIN_USER_COOKIE_KEY";

        public string GET(string key, string deft = "")
        {
            return HttpHelper.Request.GetGetString(context.Request, key, deft);
        }

        public string POST(string key, string deft = "")
        {
            return HttpHelper.Request.GetPostString(context.Request, key, deft);
        }

        public HttpPostedFile FILE(string key)
        {
            return HttpHelper.Request.GetPostFile(context.Request, key);
        }

        public List<HttpPostedFile> FILE_LIST()
        {
            return HttpHelper.Request.GetPostFileList(context.Request);
        }

        public string MAP_PATH(string path)
        {
            return HttpHelper.Server.GetMapPath(context, path);
        }

        public void SET_SESSION(string key, object value)
        {
            HttpHelper.Session.SetSession(context.Session, key, value);
        }

        public void REMOVE_SESSION(string key)
        {
            HttpHelper.Session.RemoveSession(context.Session, key);
        }

        public string GET_SESSION_STRING(string key)
        {
            return HttpHelper.Session.GetSessionString(context.Session, key);
        }

        public T GET_SESSION<T>(string key)
        {
            return HttpHelper.Session.GetSession<T>(context.Session, key);
        }

        public WebWorkContext(System.Web.HttpContext context)
        {
            if (context == null)
            {
                throw new Exception("上下文不能为空");
            }
            this.context = context;

            this.IsPost = HttpHelper.Request.IsPost(context.Request);
            this.IsAjax = HttpHelper.Request.IsAjax(context.Request);
            this.IsPostAjax = this.IsPost && this.IsAjax;
            this.IP = HttpHelper.Request.GetUserIP(context.Request);
            this.BaseUrl = HttpHelper.Request.GetBaseUrl(context.Request);
            this.Url = HttpHelper.Request.GetCurrentUrl(context.Request);
            this.UrlReferrer = HttpHelper.Request.GetUrlReferrer(context.Request);
            //检查cookie并且登陆
            CheckUserLogin();
        }

        public int getUserId()
        {
            return this.LoginUser == null ? default(int) : this.LoginUser.id;
        }

        private void CheckUserLogin()
        {
            //login user
            this.LoginUser = GET_SESSION<Sys_Users>(SESSION_KEY);
            this.LoginRole = GET_SESSION<Sys_Roles>(SESSION_ROLE);
            if (this.LoginUser != null) { return; }
            string uid = HttpHelper.Cookie.GetCookie(context, COOKIE_KEY);
            if (!ValidateHelper.IsPlumpString(uid))
            {
                return;
            }
            using (UserDal dal = new UserDal())
            {
                Sys_Users user = dal.FindModel(x => x.id.ToString() == uid);
                if (user != null)
                {
                    SetUserLogin(user, false);
                }
                else
                {
                    LogOut();
                }

                //根据用户ID获取角色
                SetRoleByUserId(int.Parse(uid));
            }
        }

        public void SetUserLogin(Sys_Users user, bool SaveCookie = false)
        {
            if (user == null) { return; }
            this.LoginUser = user;
            SET_SESSION(SESSION_KEY, user);

            if (SaveCookie)
            {
                HttpHelper.Cookie.SetCookie(context, COOKIE_KEY, user.id.ToString(), 60 * 24 * 7);
            }
        }

        /// <summary>
        /// 设置角色到session
        /// </summary>
        /// <param name="userId"></param>
        public void SetRoleByUserId(int userId)
        {
            //根据用户ID获取用户角色
            Sys_Roles role = new RoleDal().GetRoleByUserId(userId);

            this.LoginRole = role;
            SET_SESSION(SESSION_ROLE, role);
        }

        public void LogOut()
        {
            REMOVE_SESSION(SESSION_KEY);
            REMOVE_SESSION(SESSION_ROLE);
            HttpHelper.Cookie.RemoveCookie(context, COOKIE_KEY);
        }

        public HttpContext context { get; private set; }

        public bool IsPost { get; private set; }

        public bool IsAjax { get; private set; }//当前请求是否为ajax请求

        public bool IsPostAjax { get; private set; }

        public string IP { get; private set; }//用户ip

        public string BaseUrl { get; private set; }

        public string Url { get; private set; }//当前url

        public string UrlReferrer { get; private set; }//上一次访问的url

        public Sys_Users LoginUser { get; private set; }//登陆用户

        public Sys_Roles LoginRole { get; private set; }//登陆用户角色


        public void Dispose()
        {
        }
    }
}